﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;
using DataTier.Connection;

namespace DataTier.Repository
{
    /// <summary>
    /// Базовый класс для всех репозиториев
    /// </summary>
    public class RepositoryBase
    {
        readonly protected DbConnection dbConnection = null;
        public RepositoryBase()
        {
        }
        public RepositoryBase(IDbConnection connection)
        {
            this.dbConnection = (DbConnection)connection;
        }
        /// <summary>
        /// Создает DataContext
        /// </summary>
        /// <returns></returns>
        protected DBModelContainer CreateDataContext()
        {
            return dbConnection == null
                ? new DBModelContainer()
                : new DBModelContainer(dbConnection.ConnectionString);
        }
        /// <summary>
        /// Открывает новое соединение с БД или использует существующее
        /// </summary>
        /// <returns></returns>
        protected DbConnectionWrapper OpenConnection()
        {
            return new DbConnectionWrapper(this.dbConnection);
        }
        /// <summary>
        /// Обертка над DbConnection
        /// </summary>
        protected class DbConnectionWrapper : IDisposable
        {
            readonly DbConnection connection;
            /// <summary>
            /// Работаем ли мы в рамках существующего connection-а или используем свой
            /// </summary>
            readonly bool isAttachedToExistingConnection = false;
            public DbConnectionWrapper(DbConnection connection)
            {
                if (connection == null)
                {
                    this.isAttachedToExistingConnection = false;
                    this.connection = new ConnectionFactory().CreateConnection();
                    this.connection.Open();
                }
                else
                {
                    this.isAttachedToExistingConnection = true;
                    this.connection = connection;
                }
            }

            public DbCommand CreateCommand()
            {
                return this.connection.CreateCommand();
            }

            public void Dispose()
            {
                if (isAttachedToExistingConnection == false)
                    this.connection.Dispose();
            }
        }
    }
}
